package com.ruoyi.chat.service.impl;

import java.util.Collections;
import java.util.List;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.chat.domain.RequestDto;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.sun.prism.impl.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.chat.mapper.TbChatMapper;
import com.ruoyi.chat.domain.TbChat;
import com.ruoyi.chat.service.ITbChatService;

/**
 * 聊天记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-08-21
 */
@Service
public class TbChatServiceImpl extends ServiceImpl<TbChatMapper, TbChat> implements ITbChatService
{
    @Override
    public List<TbChat> getChatList() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        LambdaQueryWrapper<TbChat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbChat::getUserId,userId);
        wrapper.orderByAsc(TbChat::getChatTime);
        List<TbChat> list = this.list(wrapper);
        if (list != null) return list;
        return Collections.emptyList();
    }

    @Override
    public TbChat chat(RequestDto requestDto) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        TbChat chatRequest = new TbChat();
        chatRequest.setContent(requestDto.getContent());
        chatRequest.setChatTime(DateUtils.getNowDate());
        chatRequest.setUserId(user.getUserId());
        chatRequest.setSender(user.getUserId());
        this.save(chatRequest);
        // 使用安全认证AK/SK鉴权，替换下列示例中参数，安全认证Access Key替换your_iam_ak，Secret Key替换your_iam_sk
        Qianfan qianfan = new Qianfan("ALTAKW5EjHGwBRZvP3FHRQ23eI", "8eb661469d8f4e2c838cc472e5b31f37");
        // 指定模型
        ChatResponse resp = qianfan.chatCompletion()
                .model("ERNIE-Speed-128K")
                .addMessage("user", requestDto.getContent())
                .execute();
        String result = resp.getResult();
        TbChat chatResponse = new TbChat();
        chatResponse.setChatTime(DateUtils.getNowDate());
        chatResponse.setContent(result);
        chatResponse.setUserId(user.getUserId());
        chatResponse.setSender(0L);
        this.save(chatResponse);
        return chatResponse;
    }


}
